<?php

$id = intval($_REQUEST['id']);
$tid = intval($_REQUEST['tid']);

if (isset($_REQUEST['replymessage']))
    $msg = strval($_REQUEST['replymessage']);
else
    $msg = 'not set';

include 'inc/conn.php';
$companyname = "";
$companymail = "";
$sql = "select companyname, email from ats_company";
$res = mysql_query($sql)
        or die(json_encode(array('msg' => 'error getting company info')));
$row = mysql_fetch_row($res);
if (mysql_num_rows($res) > 0) {
    $companyname = $row[0];
    $companymail = $row[1];
}
$newmessage = 'init';

if ($tid == 5) {
    $sql = "select * from ats_contactus where id=$id";
} else {
    $sql = "select * from ats_partner_contact where id=$id";
}

$res = mysql_query($sql)
        or die(json_encode(array('msg' => 'error getting contact info')));
$row = mysql_fetch_row($res);
if (mysql_num_rows($res) > 0) {
    $to = $row[2];
    $subject = "Re: $row[4]";

    $newmessage = "
    <html>
    <head>
        <title>Re: $row[4]</title>
    </head>
    <body>
        <p>Dear $row[1],</p>
        <br />
        <p>$msg</p>
        <br />
        <br />
        <p>Regards,</p>
        <p>ATS Tour</p>
    </body>
    </html>";

    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    $headers .= "To: $row[1] <$row[2]>" . "\r\n";
    $headers .= "From: $companyname <$companymail>" . "\r\n";

    if (mail($to, $subject, $newmessage, $headers))
        $result = true;
    else
        $result = false;
}


if ($result) {
    if ($tid == 5) {
        //update contact us status to "replied"
        $sql = "update ats_contactus set status=2 where id=$id";
        mysql_query($sql);
    }
}

if ($result) {
    echo json_encode(array('success' => true));
} else {
    echo json_encode(array('msg' => 'Some errors occured. '));
}
?>
